//
//  AFNetWorkService.m
//  TBRJL
//
//  Created by zzy on 16/01/16.
//  Copyright (c) 2016年 zzy. All rights reserved.
//

#import "AFNetWorkService.h"
#import "AFURLSessionManager.h"
#import "UrlRequestModel.h"
#import "UserInfoModel.h"

@implementation AFNetWorkService
static int i = 0;
- (void)requestWithServiceIP:(NSString *) serviceIP ServiceName:(NSString *)serviceName params:(NSMutableDictionary *)params httpMethod:(NSString *)httpMethod resultIsDictionary:(BOOL)resultIsDictionary completeBlock:(RequestCompelete)block
{
    //拼接URL
    NSString *url = [NSString stringWithFormat:@"%@/%@/query",serviceIP,serviceName];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    if(!resultIsDictionary)
    {
        manager.responseSerializer = [AFCompoundResponseSerializer serializer];//响应
    }
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    if ([serviceIP isEqualToString:BAOYIURL]) {
        manager.requestSerializer.timeoutInterval = 120.0f;
    }else
    {
        manager.requestSerializer.timeoutInterval = 30.0f;
    }
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    //设置相应内容类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/plain",@"text/javascript",nil];
    
    NSArray *array = [params allKeys];
    if(array.count != 0)
    {
        for (int  i = 0; i < array.count; i++)
        {
            NSString *key = array[i];
            id object = [params objectForKey:key];
            
            //判断参数类型
            if([object isKindOfClass:[NSNumber class]])
            {
            }
            else if([object isKindOfClass:[NSString class]])
            {
            }
            else if([object isKindOfClass:[NSData class]])
            {
            }
            else
            {
                NSString *string = [self objectToJson:object];
                [params setValue:string forKey:key];
            }
        }
    }
    //添加版本号到head里面
    self.versionStr = versionNumber;
    [manager.requestSerializer setValue:(nil == self.versionStr?@"":self.versionStr) forHTTPHeaderField:@"App-Version"];
    [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"OSType"];
    if (_token.length > 0) {
        [manager.requestSerializer setValue:_token forHTTPHeaderField:@"apptoken"];
    }
    NSString *bbkey = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    if (bbkey.length > 0) {
        [manager.requestSerializer setValue:bbkey forHTTPHeaderField:@"bbkey"];
    }else
    {
        NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        bbkey = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/uuidString.plist",doc] encoding:NSUTF8StringEncoding error:nil];
        if (  bbkey.length == 0) {
            bbkey =  [self getUniqueStrByUUID];
            [bbkey writeToFile:[NSString stringWithFormat:@"%@/uuidString.plist",doc] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
        [manager.requestSerializer setValue:bbkey forHTTPHeaderField:@"bbkey"];
    }
    NSLog(@"%@",[manager.requestSerializer HTTPRequestHeaders]);
    //处理POST的参数
    NSComparisonResult compareRet = [httpMethod caseInsensitiveCompare:@"POST"];
    if(NSOrderedSame == compareRet)
    {
        [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *responseString;
            BOOL isrespons = NO;
            if ([responseObject isKindOfClass:[NSData class]]) {
                responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                if ([responseString isEqualToString:@""] || responseString == nil) {
                    isrespons = NO;
                }else
                {
                    isrespons = YES;
                }
            }else
            {
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *dic = (NSDictionary *)responseObject;
                    
                    if ([dic allKeys].count > 0) {
                        isrespons = YES;
                    }else
                    {
                        isrespons = NO;
                    }
                }else
                {
                    if (responseObject != nil) {
                        isrespons = YES;
                    }else
                    {
                        isrespons = NO;
                    }
                }
            }
            UrlRequestModel *model = [UrlRequestModel mj_objectWithKeyValues:responseObject];
            if (model.resultstate == 4003 || model.resultstate == 4004) {
                NSHTTPURLResponse * response = (NSHTTPURLResponse *)task.response;
                if(isrespons)
                {
                    if(nil != self.requestInfo && response.statusCode == 200)
                    {
                        _count++;
                        if(self.count > 3)
                        {
                            self.count = 0;
                            i = 0;
                            block(nil);
                        }
                        else
                        {
                            //获取新的cookID
                            [self getCookIdSeviceIP:serviceIP ServiceName:serviceName params:params httpMethod:httpMethod resultIsDictionary:resultIsDictionary completeBlock:block];
                        }
                        return;
                    }
                }
            }else
            {
                
                if(block != nil)
                {
                    self.count = 0;
                    i = 0 ;
                    block(resultIsDictionary ? responseObject:responseString);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"调用服务出错(POST)");
            if(block != nil)
            {
                self.count = 0;
                i = 0;
                block(nil);
            }
        }];
    }
    else
    {
        [manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSString *responseString;
            BOOL isrespons = NO;
            if ([responseObject isKindOfClass:[NSData class]]) {
                responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
                if ([responseString isEqualToString:@""] || responseString == nil) {
                    isrespons = NO;
                }else
                {
                    isrespons = YES;
                }
            }else
            {
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *dic = (NSDictionary *)responseObject;
                    
                    if ([dic allKeys].count > 0) {
                        isrespons = YES;
                    }else
                    {
                        isrespons = NO;
                    }
                }else
                {
                    if (responseObject != nil) {
                        isrespons = YES;
                    }else
                    {
                        isrespons = NO;
                    }
                }
            }
            UrlRequestModel *model = [UrlRequestModel mj_objectWithKeyValues:responseObject];
            if (model.resultstate == 4003 || model.resultstate == 4004) {
                NSHTTPURLResponse * response = (NSHTTPURLResponse *)task.response;
                if(isrespons)
                {
                    if(nil != self.requestInfo && response.statusCode == 200)
                    {
                        _count++;
                        if(self.count > 3)
                        {
                            self.count = 0;
                            i = 0;
                            block(nil);
                        }
                        else
                        {
                            //获取新的cookID
                            [self getCookIdSeviceIP:serviceIP ServiceName:serviceName params:params httpMethod:httpMethod resultIsDictionary:resultIsDictionary completeBlock:block];
                        }
                        return;
                    }
                }
            }else
            {
                if(block != nil)
                {
                    self.count = 0;
                    i = 0;
                    block(resultIsDictionary ? responseObject:responseString);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"调用服务出错(GET)");
            if(block != nil)
            {
                self.count = 0;
                i = 0;
                block(nil);
            }
        }];
    }
}

- (NSString *)getUniqueStrByUUID {
    CFUUIDRef uuidRef = CFUUIDCreate(NULL);
    CFStringRef uuidStrRef= CFUUIDCreateString(NULL, uuidRef);
    CFRelease(uuidRef);
    NSString *retStr = [NSString stringWithString:(__bridge NSString * _Nonnull)(uuidStrRef)];
    CFRelease(uuidStrRef);
    return retStr;
}

-(void)getCookIdSeviceIP:(NSString *) serviceIP ServiceName:(NSString *)serviceName params:(NSMutableDictionary *)params httpMethod:(NSString *)httpMethod resultIsDictionary:(BOOL)resultIsDictionary completeBlock:(RequestCompelete)block
{
    //拼接URL
    i++;
    NSString *url = [NSString stringWithFormat:@"%@/%@/query",self.requestInfo.serviceIP,self.requestInfo.serviceName];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    if(!resultIsDictionary)
    {
        manager.responseSerializer = [AFCompoundResponseSerializer serializer];//响应
    }
    //设置相应内容类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/plain",@"text/javascript",nil];
    
    NSArray *array = [self.requestInfo.params allKeys];
    if(array.count != 0)
    {
        for (int  i = 0; i < array.count; i++)
        {
            NSString *key = array[i];
            id object = [self.requestInfo.params objectForKey:key];
            
            //判断参数类型
            if([object isKindOfClass:[NSNumber class]])
            {
                
            }
            else if([object isKindOfClass:[NSString class]])
            {
                
            }
            else if([object isKindOfClass:[NSData class]])
            {
                
            }
            else
            {
                NSString *string = [self objectToJson:object];
                [self.requestInfo.params setValue:string forKey:key];
            }
        }
    }
    //处理POST的参数
    self.versionStr = versionNumber;
    [manager.requestSerializer setValue:(nil == self.versionStr?@"":self.versionStr) forHTTPHeaderField:@"App-Version"];
    [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"OSType"];
    if (_token.length > 0) {
        [manager.requestSerializer setValue:_token forHTTPHeaderField:@"apptoken"];
    }
    NSString *bbkey = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    if (bbkey.length > 0) {
        [manager.requestSerializer setValue:bbkey forHTTPHeaderField:@"bbkey"];
    }else
    {
        NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        bbkey = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/uuidString.plist",doc] encoding:NSUTF8StringEncoding error:nil];
        if (  bbkey.length == 0) {
            bbkey =  [self getUniqueStrByUUID];
            [bbkey writeToFile:[NSString stringWithFormat:@"%@/uuidString.plist",doc] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
        [manager.requestSerializer setValue:bbkey forHTTPHeaderField:@"bbkey"];
    }
    
    NSComparisonResult compareRet = [self.requestInfo.httpMethod caseInsensitiveCompare:@"POST"];
    if(NSOrderedSame == compareRet)
    {
        [manager POST:url parameters:self.requestInfo.params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //发送成功通知
            UserInfoModel *userinfo = [UserInfoModel mj_objectWithKeyValues:responseObject];
            _token = userinfo.result.apptoken;
            NSString *responseString;
            if ([responseObject isKindOfClass:[NSData class]]) {
                responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            }
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:@"LoginForGetCookId" object:resultIsDictionary ? responseObject:responseString];
            //成功，继续调用当前服务
            if (i <= 3)
            {
                [self requestWithServiceIP:serviceIP ServiceName:serviceName params:params httpMethod:httpMethod resultIsDictionary:resultIsDictionary completeBlock:block];
            }else
            {
                i = 0;
                self.count = 0;
                if(block != nil)
                {
                    block(nil);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //发送失败通知
            i = 0;
            self.count = 0;
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:@"LoginForGetCookId" object:nil];
            if(block != nil)
            {
                block(nil);
            }
        }];
    }
    else
    {
        [manager GET:url parameters:self.requestInfo.params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //发送成功通知
            NSString *responseString;
            if ([responseObject isKindOfClass:[NSData class]]) {
                responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            }
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:@"LoginForGetCookId" object:resultIsDictionary ? responseObject:responseString];
            //成功，继续调用当前服务
            if (i <= 3)
            {
                [self requestWithServiceIP:serviceIP ServiceName:serviceName params:params httpMethod:httpMethod resultIsDictionary:resultIsDictionary completeBlock:block];
            }else
            {
                i = 0;
                self.count = 0;
                if(block != nil)
                {
                    block(nil);
                }
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //发送失败通知
            i = 0;
            self.count = 0;
            NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
            [center postNotificationName:@"LoginForGetCookId" object:nil];
            
            if(block != nil)
            {
                block(nil);
            }
        }];
    }
}
- (NSString*)objectToJson:(NSObject *)object
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

#pragma mark - 多个图片上传
- (void)uploadMutableimgWithWithServiceIP:(NSString *)serviceIP ServiceName:(NSString *)serviceName  Withparameter:(NSDictionary *)parameter imagesarray:(NSMutableArray *)imgarray progress:(void (^)(NSProgress * progress))progress success:(void (^)())success fail:(void (^)())fail
{
    NSString *url = [NSString stringWithFormat:@"%@/%@/query",serviceIP,serviceName];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/plain",@"text/javascript",nil];
    self.versionStr = versionNumber;
    [manager.requestSerializer setValue:(nil == self.versionStr?@"":self.versionStr) forHTTPHeaderField:@"App-Version"];
    [manager.requestSerializer setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [manager.requestSerializer setValue:@"iOS" forHTTPHeaderField:@"OSType"];
    if (_token.length > 0) {
        [manager.requestSerializer setValue:_token forHTTPHeaderField:@"apptoken"];
    }
    NSString *bbkey = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    if (bbkey.length > 0) {
        [manager.requestSerializer setValue:bbkey forHTTPHeaderField:@"bbkey"];
    }else
    {
        NSString *doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
        bbkey = [[NSString alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/uuidString.plist",doc] encoding:NSUTF8StringEncoding error:nil];
        if (  bbkey.length == 0) {
            bbkey =  [self getUniqueStrByUUID];
            [bbkey writeToFile:[NSString stringWithFormat:@"%@/uuidString.plist",doc] atomically:YES encoding:NSUTF8StringEncoding error:nil];
        }
        [manager.requestSerializer setValue:bbkey forHTTPHeaderField:@"bbkey"];
    }
    [manager POST:url parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        /*文件命名参考代码
         // 在网络开发中，上传文件时，是文件不允许被覆盖，文件重名
         // 要解决此问题，
         // 可以在上传时使用当前的系统事件作为文件名
         NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
         // 设置时间格式
         formatter.dateFormat = @"yyyyMMddHHmmss";
         NSString *str = [formatter stringFromDate:[NSDate date]];
         NSString *newfileName = [NSString stringWithFormat:@"%@.png", str];
         */
        for (int i=0; i<[imgarray count]; i++) {
            [formData appendPartWithFileData:UIImageJPEGRepresentation([imgarray objectAtIndex:i],0.5) name:[NSString stringWithFormat:@"file%d",i ] fileName:[NSString stringWithFormat:@"pic%d.jpg",i] mimeType:@"image/jpg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if (progress) {
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSData class]]) {
            NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            NSLog(@"%@",responseString);
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail();
        }
    }];
}
@end
